package cn.kgc.controller;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class shangchuanController {

    /*ajax实现文件上传并预览*/
    @RequestMapping("/testFileUpload")
    @ResponseBody
    public Map<String, Object> testFileUpload(@RequestParam(value = "idPic", required = false) MultipartFile idPic,
                                              HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();

        String path = session.getServletContext().getRealPath("static" + File.separator + "images" + File.separator + "uploadfile");
        if (idPic != null) {
            if (idPic.getSize() > 1 * 1024 * 1024) {
                map.put("msg", "上传不能超过1M");
                map.put("status", "error");
                map.put("filename", "");
                return map;
            }
            System.out.println(path);
            //获取原文件名
            String oldFileName = idPic.getOriginalFilename();
            System.out.println(oldFileName);
            //获取扩展名
            String prefix = FilenameUtils.getExtension(oldFileName);//原文件后缀
            List<String> prefixs = new ArrayList<>();
            prefixs.add("jpg");
            prefixs.add("JPG");
            prefixs.add("png");
            prefixs.add("jpeg");
            prefixs.add("pneg");
            if (prefixs.contains(prefix) == false) {
                map.put("msg", "上传图片格式不正确");
                map.put("status", "error");
                map.put("filename", "");
                return map;
            }
            System.out.println(prefix);
            //生成新文件名
            String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + prefix;
            System.out.println(fileName);
            //封装文件对象
            File targetFile = new File(path, fileName);

            try {
                idPic.transferTo(targetFile);
                map.put("status", "true");
                map.put("msg", "文件上传成功");
                map.put("filename", fileName);
                return map;
            } catch (IOException e) {
                e.printStackTrace();
                map.put("status", "error");
                map.put("msg", e.getMessage());
                map.put("filename", fileName);
                return map;
            }
        }
        return map;
    }
/*多文件上传*/
//测试多文件上传
@RequestMapping("/testUpload_more")
public String testUpload_more(MultipartFile idPic,
                              MultipartFile idPic2,
                              Model model, HttpSession session) {
    //上传idPic
    int filesize = 1024 * 1024;
    if (idPic.getSize() > filesize) {
        model.addAttribute("errormsg", "文件最大仅支持1M !!!");
        return "file";
    }
    //获取路径
    String path = session.getServletContext().getRealPath("images" + File.separator + "uploadfile");
    System.out.println(path);
    //获取旧文件名
    String oldFileName = idPic.getOriginalFilename();
    //拓展名
    String ext = FilenameUtils.getExtension(oldFileName);
    System.out.println("拓展名：" + ext);
    //生成新的文件名
    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + ext;
    System.out.println(fileName);
    //验证文件格式
    List<String> prefixs = new ArrayList<>();
    prefixs.add("jpg");
    prefixs.add("png");
    if (prefixs.contains(ext) == false) {
        model.addAttribute("errormsg", "仅支持jpg,png文件");
        return "file";
    }
    //上传文件
    File file = new File(path, fileName);
    try {
        idPic.transferTo(file);
    } catch (IOException e) {
        e.printStackTrace();
    }

    //上传idPic2
    if (idPic2.getSize() > filesize) {
        model.addAttribute("errormsg", "文件最大仅支持1M !!!");
        return "file";
    }
    //获取路径          获取工程目录
    String path2 = session.getServletContext().getRealPath("images" + File.separator + "uploadfile");
    System.out.println(path);
    //获取旧文件名
    String oldFileName2 = idPic2.getOriginalFilename();
    //拓展名
    String ext2 = FilenameUtils.getExtension(oldFileName2);
    System.out.println("拓展名：" + ext);
    //生成新的文件名
    String fileName2 = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + ext;
    System.out.println(fileName2);
    //验证文件格式
        /*List<String> prefixs=new ArrayList<>();
        prefixs.add("jpg");
        prefixs.add("png");*/
        /*if(prefixs.contains(ext)==false){
            model.addAttribute("errormsg","仅支持jpg,png文件");
            return "file";
        }*/
    //上传文件
    File file2 = new File(path2, fileName2);
    try {
        idPic2.transferTo(file2);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "body/upload_success";
}





  /*  *//*springmvc方式下载*//*
    @RequestMapping("/download.do")
    @ResponseBody
    public void down(String filename, HttpServletRequest request, HttpServletResponse response) {
        String realPath = request.getServletContext().getRealPath("images" + File.separator + "uploadfile");
        File file = new File(realPath, filename);
        //设置响应类型  ==》 告诉浏览器当前是下载操作，我要下载东西
        response.setContentType("application/x-msdownload");
        //设置下载时文件的显示类型(即文件名称-后缀)   ex：txt为文本类型
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        //下载文件：将一个路径下的文件数据转到一个输出流中，也就是把服务器文件通过流写(复制)到浏览器端
        try {
            Files.copy(file.toPath(), response.getOutputStream());//Files.copy(要下载的文件的路径,响应的输出流)
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

*/


}






